package cn.foolapi.api.utils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

//GOTO foolapi数据库校验支持工具类
/**
 * 
 * @author keny.jiang
 * @date 2019-09
 *
 */
public class MysqlUtil {
	private static String DB_URL;
	private static String JDBC_DRIVER;
	private static String USER;
	private static String PASSWORD;

	public MysqlUtil() throws FileNotFoundException, IOException {
		Properties pps = new Properties();
		pps.load(new FileInputStream("config.properties"));
		DB_URL = pps.getProperty("DB_URL");
//		DB_URL = "jdbc:mysql://127.0.0.1:3306/test?useSSL=false&autoReconnect=true&failOverReadOnly=false&maxReconnects=10";
		JDBC_DRIVER = pps.getProperty("JDBC_DRIVER");
		USER = pps.getProperty("USER");
		PASSWORD = pps.getProperty("PASSWORD");
	}

	public Map getSql(String sql)
			throws FileNotFoundException, IOException, InstantiationException, IllegalAccessException, SQLException {

		MysqlUtil mu = new MysqlUtil();
		Connection connection = mu.getcon();
		Statement stmt = connection.createStatement();
		ResultSet rs = stmt.executeQuery(sql);

		ResultSetMetaData data = rs.getMetaData();
		Map map = new HashMap();
		// 遍历数据库表字段名和类型
		for (int i = 1; i <= data.getColumnCount(); i++) {
			map.put(data.getColumnName(i), data.getColumnClassName(i));
		}
		// 展开结果集数据库
		while (rs.next()) {
			// 通过字段检索
			Iterator entries = map.entrySet().iterator();
			while (entries.hasNext()) {
				Map.Entry entry = (Map.Entry) entries.next();
				String key = (String) entry.getKey();
				String value = (String) entry.getValue();
				switch (value) {
				case "java.lang.String":
					map.put(key, rs.getString(key));
					break;
				case "java.lang.Integer":
					map.put(key, rs.getInt(key));
					break;
				case "java.lang.Byte":
					map.put(key, rs.getByte(key));
					break;
				case "java.lang.Date":
					map.put(key, rs.getDate(key));
					break;
				case "java.lang.Long":
					map.put(key, rs.getLong(key));
					break;
				default:
					map.put(key, "未知数据类型");
					break;
				}
			}
		}
		// 完成后关闭
		rs.close();
		stmt.close();
		connection.close();
		
		//返回map集合
		return map;

	}

	private Connection getcon() throws InstantiationException, IllegalAccessException {
		Connection conn = null;
		try {
			// 注册 JDBC 驱动
			Class.forName(JDBC_DRIVER).newInstance();
			conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
			return conn;
		} catch (SQLException e) {
			ReportUtil.log("SQLException:" + e.getMessage());
			return null;
		} catch (ClassNotFoundException e) {
			ReportUtil.log("ClassNotFoundException:" + e.getMessage());
			return null;
		}
	}

}